package ace.module.product.core.impl.manager.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.model.SaveContext;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.utils.SaveContextUtils;
import ace.module.common.core.impl.manager.impl.AbstractEntityOfAppManager;
import ace.module.product.api.model.dto.PmsProductStatisticDto;
import ace.module.product.core.impl.dao.entity.PmsProduct;
import ace.module.product.core.impl.dao.entity.PmsProductStatistic;
import ace.module.product.core.impl.dao.repository.PmsProductStatisticRepository;
import ace.module.product.core.impl.manager.PmsProductStatisticManager;
import java.util.Objects;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 商品统计数据,非实时 spring data jdbc querydsl rsql manager implement.
 *
 * @author Caspar
 */
@Slf4j
@AllArgsConstructor
@Component
public class PmsProductStatisticManagerImpl
    extends AbstractEntityOfAppManager<PmsProductStatistic, Long, PmsProductStatisticDto>
    implements PmsProductStatisticManager {

  private final PmsProductStatisticRepository pmsProductStatisticRepository;

  @Override
  public SaveContext<PmsProductStatistic> assembleSaveContext(SaveContext<PmsProduct> pmsProductSaveContext) {
    PmsProduct pmsProduct = pmsProductSaveContext.getData();
    PmsProductStatistic pmsProductStatistic = pmsProductStatisticRepository.findByPmsAppIdAndProductIdAndDeleteFlag(pmsProduct.getPmsAppId(), pmsProduct.getId(), CoreConstant.DELETE_FLAG_NOT);
    if (Objects.nonNull(pmsProductStatistic)) {
      return SaveContextUtils.empty();
    }
    pmsProductStatistic = PmsProductStatistic.builder()
        .id(this.getNewId())
        .pmsAppId(pmsProduct.getPmsAppId())
        .productId(pmsProduct.getId())
        .score(CoreConstant.ZERO_LONG)
        .commentCount(CoreConstant.ZERO_LONG)

        .deleteFlag(CoreConstant.DELETE_FLAG_NOT)
        .createTime(System.currentTimeMillis())
        .updateTime(System.currentTimeMillis())
        .rowVersion(CoreConstant.DEFAULT_ROW_VERSION)
        .build();

    return SaveContextUtils.ofNew(pmsProductStatistic);
  }
}
